package com.cloud.form.api.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.cloud.form.api.entity.FormAssemblyInst;
import com.cloud.form.api.entity.FormValue;
import com.cloud.form.api.mapper.FormAssemblyInstMapper;
import com.cloud.form.api.mapper.FormValueMapper;
import com.cloud.form.api.service.FormValueService;
import com.cloud.form.api.translator.CalendarTranslator;
import com.cloud.form.api.translator.CheckboxTranslator;
import com.cloud.form.api.translator.DropDownTranslator;
import com.cloud.form.api.translator.ImageTranslator;
import com.cloud.form.api.translator.InputTranslator;
import com.cloud.form.api.translator.RadioTranslator;
import com.cloud.form.api.translator.TableTranslator;
import com.cloud.form.api.translator.TextAreaTranslator;
import com.cloud.form.common.exception.BizException;

@Service
public class FormValueServiceImpl implements FormValueService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private FormValueMapper formValueMapper;

	@Autowired
	private FormAssemblyInstMapper formAssemblyInstMapper;

	@Override
	public void saveUpdateFormValue(FormValue content) {
		if (formValueMapper.existsWithPrimaryKey(content)) {
			formValueMapper.updateByPrimaryKey(content);
		} else {
			formValueMapper.insert(content);
		}
	}

	@Override
	public FormValue loadFormValue(FormValue value) {
		return formValueMapper.selectByPrimaryKey(value);
	}

	@Override
	public byte[] printView(FormValue value) {
		// 1.取出文书值
		FormValue filledValue = formValueMapper.selectByPrimaryKey(value);
		// 2.取出文书模板
		List<String> fileContents = jdbcTemplate.queryForList("select form_print from form_def where form_id = ?",
				String.class, value.getFormId());
		byte[] fileBytes = null;
		if (null != fileContents && fileContents.size() > 0 && !StringUtils.isEmpty(fileContents.get(0))) {
			fileBytes = Base64.getDecoder().decode(fileContents.get(0));
		} else {
			throw new BizException(500, "未上传输出文书模板！");
		}
		byte[] fileContent = null;
		Document doc = null;
		ByteArrayInputStream bis = null;
		ByteArrayOutputStream bos = null;
		try {
			bis = new ByteArrayInputStream(fileBytes);
			doc = new Document(bis);
			// 3.关联文书值到模板对应的位置
			JSONArray formValueArray = JSON.parseArray(filledValue.getFormValue());
			@SuppressWarnings("rawtypes")
			Iterator it = formValueArray.iterator();
			while (it.hasNext()) {
				JSONObject formFieldValue = (JSONObject) it.next();
				Long fieldId = formFieldValue.getLong("id");
				String fieldName = formFieldValue.getString("name");
				String fieldValue = formFieldValue.getString("value");
				if (!StringUtils.isEmpty(fieldValue) && !StringUtils.isEmpty(fieldName) && !"null".equals(fieldName)) {
					FormAssemblyInst fieldInst = formAssemblyInstMapper.selectByPrimaryKey(fieldId);
					switch (fieldInst.getControlType()) {
					case "input":
						InputTranslator.translator(doc, fieldName, fieldValue, fieldInst);
						break;
					case "textarea":
						TextAreaTranslator.translator(doc, fieldName, fieldValue, fieldInst);
						break;
					case "calendar":
						CalendarTranslator.translator(doc, fieldName, fieldValue, fieldInst);
						break;
					case "radio":
						RadioTranslator.translator(doc, fieldName, fieldValue, fieldInst);
						break;
					case "checkbox":
						CheckboxTranslator.translator(doc, fieldName, fieldValue, fieldInst);
						break;
					case "dropdown":
						DropDownTranslator.translator(doc, fieldName, fieldValue, fieldInst);
					case "image":
						ImageTranslator.translator(doc, fieldName, fieldValue, fieldInst);
						break;
					case "table":
						TableTranslator.translator(doc, fieldName, fieldValue, fieldInst);
						break;
					default:
						break;
					}
				}
			}
			bos = new ByteArrayOutputStream();
			doc.save(bos, SaveFormat.DOC);
			fileContent = bos.toByteArray();
			bos.flush();
			return fileContent;
		} catch (Exception e) {
			throw new RuntimeException("文件解析失败", e);
		} finally {
			try {
				if (null != bis)
					bis.close();
				if (null != bos)
					bos.close();
			} catch (Exception e) {
			}
		}
	}

}
